package com.cata.mall.security.component;

import cn.hutool.json.JSONUtil;
import com.cata.mall.common.api.CommonResult;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @作者: Tao
 * @日期: 2025/10/11
 * @时间: 11:07
 * @描述: 自定义无权限访问的返回结果<pre>
 */
public class RestfulAccessDeniedHandler implements AccessDeniedHandler {
    /**
     * 处理访问拒绝异常，返回JSON格式的错误响应
     *
     * @param request HTTP请求对象
     * @param response HTTP响应对象
     * @param accessDeniedException 访问拒绝异常对象
     * @throws IOException IO异常
     * @throws ServletException Servlet异常
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        // 设置跨域访问权限和缓存控制
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control","no-cache");

        // 设置响应编码和内容类型
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");

        // 返回访问拒绝的JSON格式错误信息
        response.getWriter().println(JSONUtil.parse(CommonResult.forbidden(accessDeniedException.getMessage())));
        response.getWriter().flush();
    }

}
